package com.kaibes.platform.file.server;

import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.crypto.BadPaddingException;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.kaibes.core.base.util.AesUtils;

@Component
public class FileTokenHelper {

    @Autowired
    private ObjectMapper objectMapper;
    
    public String readString(FileClient fileClient, String str) {
        try {
            str = AesUtils.CBC.decrypt2String64(str, fileClient.getAesKey(), fileClient.getAesIv());
            return str;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
//            e.printStackTrace();
            return null;
        }
    }
    
    public List<String> readListString(FileClient fileClient, String listString) {
        try {
            listString = AesUtils.CBC.decrypt2String64(listString, fileClient.getAesKey(), fileClient.getAesIv());
            return objectMapper.readValue(listString, new TypeReference<ArrayList<String>>() {});
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
    public String writeObject(FileClient fileClient, Object obj) {
        try {
            String fileStr = objectMapper.writeValueAsString(obj);
            fileStr = AesUtils.CBC.encrypt2String64(fileStr, fileClient.getAesKey(), fileClient.getAesIv());
            return fileStr;
        } catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
                | InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException | IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    
}
